<template>
    <div>
        <el-dialog
            v-model="baseVisib"
            custom-class="app_base_dialog dialog_body_noPadding"
            width="815px"
            :before-close="closeDialog">
            <template #title>
                <div class="dialog_header">素材库选择</div>
            </template>
            <!-- tab -->
            <div class="tab_box">
                <el-tabs v-model="prop.activeName" class="demo-tabs" @tab-change="handleClick">
                    <el-tab-pane v-for="item in prop.tabsList" :key="item.label" :label="item.name" :name="item.label">
                        <div class="pane-box">
                            <el-input
                                v-model="item.seachKey"
                                placeholder="搜索标题或文件名"
                                type="text"
                                :prefix-icon="Search"
                                @input="seachListFun">
                            </el-input>
                            <div class="pane-body-box">
                                <component
                                    :is="item.comName"
                                    v-if="item.label === prop.activeName && baseVisib"
                                    :multiple="multiple"
                                    :page-data="item.list"
                                    :choose-data="dialogData[item.label].list"
                                    :single-image="singleImage"
                                    :base-num="base_num"
                                    @getData="getDataFun" />
                            </div>
                            <ZWPagination ref="PaginationRef" @submit="getPage" />
                        </div>
                    </el-tab-pane>
                </el-tabs>
                <el-scrollbar class="group_box">
                    <Grouping :tree-data="treeData" @submit="getChildGroup"></Grouping>
                </el-scrollbar>

                <!-- <div class="r_tab">
            <el-button plain type="text" @click="getChildData">刷新</el-button>
            <span>不存在？去添加</span>
        </div> -->
            </div>
            <template #footer>
                <div class="footer_box">
                    <div class="right_footer">
                        <!-- :on-change="handleChange" :file-list="fileList"-->
                        <el-upload
                            v-if="localUploadShow == 'upload'"
                            class="upload_demo"
                            :accept="localUploadAllowFileType"
                            :multiple="false"
                            :show-file-list="false"
                            :on-change="handleChange"
                            :file-list="uploadFileList"
                            :http-request="function () {}">
                            <el-button type="primary" plain>本地上传</el-button>
                        </el-upload>
                        <el-button v-if="localUploadShow == 'link'" type="primary" plain @click="showCreatLocalLink">{{
                            prop.activeName == 'link' ? '创建链接' : '本地上传'
                        }}</el-button>
                        <el-button class="ml20" type="primary" @click="submitHandel">保存</el-button>
                    </div>
                    <!-- <div v-show="prop.activeName != 'text'" class="left_footer">
            已选择<span>{{ chooseCirclName[prop.activeName].num }}</span>
            {{ `${prop.activeName == 'image' ? '张' : '个'}` }}
            {{ chooseCirclName[prop.activeName].name }}, 您还可选<span>{{ base_num }}</span>
            个素材
            </div> -->
                </div>
            </template>
            <CreateLocalLink ref="CreateLocalLinkCompent" @getLocalLink="getLocalLink" />
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, defineEmits, defineExpose, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getGroupList, getImageList, linkList, getTextList, getCollectList } from '@/api/concreation';
import { GetVideoList } from '@/api/media.ts';
import { store } from '@/store/index';
const emit = defineEmits(['save']);
import { Search } from '@element-plus/icons-vue';
import Dialog from '@/components/Dialog.vue';
import Grouping from './Grouping.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import ImageList from './ImageList.vue';
import VideoList from './VideoList.vue';
import LinkList from './LinkList.vue';
import TextList from './TextList.vue';
import CollectList from './CollectList.vue';
import { uploadFile2 } from '@/api/common';
import { UploadFile } from 'element-plus/es/components/upload/src/upload';
import { getVideoThumb } from '@/utils/utils';
import CreateLocalLink from '@/view/content/friendcirclemat/components/CreateLocalLink.vue';

const CreateLocalLinkCompent = ref(null);
const uploadFileList = ref([]);
// 是否只能选择一张图片
const singleImage = ref(false);
const imgLength = ref(0);
const remainNumber = ref(0); // 剩余数量
const selet_num = ref(0); // 选中的数量
// 1-文本 2-图片 3-音频 4-视频 5-文件 6-链接文章 7-链接引用 8-朋友圈素材 || 收集表
const typeArr = [
    { type: 'text', id: 1 },
    { type: 'image', id: 2 },
    { type: 'audio', id: 3 },
    { type: 'video', id: 4 },
    { type: 'file', id: 5 },
    { type: 'link', id: 6 },
    { type: 'text', id: 7 },
    { type: 'form', id: 27 }
    // { type: 'friend', id: 8 }
];

const chooseCirclName = reactive({
    image: {
        name: '图片',
        num: 0
    },
    text: {
        name: '文本',
        num: 0
    },
    video: {
        name: '视频',
        num: 0
    },
    link: {
        name: '链接',
        num: 0
    },
    form: {
        name: '收集表',
        num: 0
    }
});
const baseVisib = ref(false);
const prop = reactive({
    activeName: 'image',
    dataTypeLimit: {
        image: singleImage.value ? 1 : 9,
        text: 100,
        video: 1,
        link: 1,
        form: 4
    }, //素材限制
    tabsList: [],
    chooseGroupId: {} //当前选中的数据类型下的分组信息
});
const getPage = (val: any) => {
    getChildData(val);
};
// 选中的数据
const dialogData = reactive({
    image: {
        page: 1,
        page_size: 15,
        seachKey: '',
        groupData: { id: '' },
        list: []
    },
    text: {
        page: 1,
        page_size: 15,
        seachKey: '',
        groupData: { id: '' },
        list: []
    },
    video: {
        page: 1,
        page_size: 15,
        seachKey: '',
        groupData: { id: '' },
        list: []
    },
    link: {
        page: 1,
        page_size: 15,
        seachKey: '',
        groupData: { id: '' },
        list: []
    },
    form: {
        page: 1,
        page_size: 15,
        seachKey: '',
        groupData: { id: '' },
        list: []
    }
});

const base_num = computed(() => {
    return prop.dataTypeLimit[prop.activeName] - remainNumber.value - selet_num.value;
});
function reinit() {
    // 清空选中信息
    for (const i in dialogData) {
        if (chooseCirclName[i]) {
            chooseCirclName[i].num = 0;
        }
        if (dialogData[i]['list']) {
            dialogData[i].num = 0;
            dialogData[i].list = [];
        }
    }
}
let t = null;
const throttle = (cd, time = 300) => {
    clearTimeout(t);
    t = setTimeout(() => {
        // eslint-disable-next-line no-undef
        const args = arguments;
        cd.call(this, args);
        t = null;
    }, time);
};
// 获取当前tab数据
const getChildData = async (val?: any) => {
    const index = prop.tabsList.findIndex(it => {
        return it.label === prop.activeName;
    });
    let data = [];
    const { seachKey, groupData } = dialogData[prop.activeName];
    const paramData = {
        page: val?.page || 1,
        page_size: val?.page_size || 15,
        title: seachKey,
        group_id: groupData.id
    };
    // 0  图片   1 视频  2链接  3 文本 4 收集表
    if (index === 0) {
        data = await getImageListFun(paramData);
    }
    if (index === 1) {
        data = await getVideoListFun(paramData);
    }
    if (index === 2) {
        data = await getLinkListFun(paramData);
    }
    if (index === 3) {
        data = await getTextListFun(paramData);
    }
    if (index === 4) {
        paramData.title = undefined;
        paramData.keyword = seachKey;
        data = await getFormList(paramData);
    }

    data.forEach(item => {
        if (dialogData[prop.activeName].list.length > 0 && prop.activeName != 'text') {
            chooseCirclName[prop.activeName].num = dialogData[prop.activeName].list.length;
            dialogData[prop.activeName].list = dialogData[prop.activeName].list.filter(
                (it: any) => (item.isCheck = it.id == item.id)
            );
        }
    });

    // dialogData[prop.activeName].list = data
    prop.tabsList[getNowTabIndex()].list = data;
};
// 输入框搜索数据
const seachListFun = (val: string) => {
    throttle(() => {
        const regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gim,
            regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/gim;
        const str = val.trim();
        if (regEn.test(val) || regCn.test(val)) {
            let str = val.replace(regEn, '');
            str = str.replace(regCn, '');
        }
        dialogData[prop.activeName].seachKey = str;
        prop.tabsList[getNowTabIndex()].seachKey = str;
        getChildData();
    }, 500);
};

// 获取当前类型的索引
const getNowTabIndex = () => {
    return prop.tabsList.findIndex(it => {
        return it.label === prop.activeName;
    });
};

const treeData = ref([]); //分组信息
// 获取分组数据
const getGroupListFun = (val?: number) => {
    return new Promise((res, ref) => {
        getGroupList({ type: val || 1 }).then((r: any) => {
            treeData.value = r.data;
            if (!dialogData[prop.activeName].groupData.id) {
                prop.tabsList[getNowTabIndex()].groupData = r.data[0];
                dialogData[prop.activeName].groupData = r.data[0];
            }
            res();
        });
    });
};

// 获取当前子组件当中的分组数据
const getChildGroup = (val: any) => {
    CreateLocalLinkCompent.value.groupId = val.id;
    prop.tabsList[getNowTabIndex()].groupData = val;
    dialogData[prop.activeName].groupData = val;
    getChildData();
};
// 监听弹框打卡
watch(baseVisib, async value => {
    if (value) {
        const typeIndex = typeArr.findIndex(it => {
            return it.type === prop.activeName;
        });
        prop.tabsList = [
            {
                name: '图片',
                label: 'image',
                list: reactive([]),
                comName: ImageList,
                page: 1,
                page_size: 15,
                seachKey: '',
                groupData: {}
            },
            {
                name: '视频',
                label: 'video',
                list: reactive([]),
                comName: VideoList,
                page: 1,
                page_size: 15,
                seachKey: '',
                groupData: {}
            },
            {
                name: '链接',
                label: 'link',
                list: reactive([]),
                comName: LinkList,
                page: 1,
                page_size: 15,
                seachKey: '',
                groupData: {}
            },
            {
                name: '文本',
                label: 'text',
                list: reactive([]),
                comName: TextList,
                page: 1,
                page_size: 15,
                seachKey: '',
                groupData: {}
            },
            {
                name: '收集表',
                label: 'form',
                list: reactive([]),
                comName: CollectList,
                page: 1,
                page_size: 15,
                seachKey: '',
                groupData: {}
            }
            // { name: "文件", label: "file" },
        ];
        await getGroupListFun(typeArr[typeIndex].id);
        getChildData();
    } else {
        selet_num.value = 0;
    }
});

// 获取图片列表数据
const getImageListFun = (param: any) => {
    return new Promise((res, ref) => {
        getImageList(param)
            .then((r: any) => {
                res(r.data);
                store.dispatch('pageTotal', r.total);
            })
            .catch((error: any) => {
                // console.log(error);
            });
    });
};

// 获取视频连接
const getVideoListFun = (param: object) => {
    param.is_radar = -1; // 类型：是否是雷达图， 未选中为 -1 ，否为0 ，是为 1
    return new Promise((res, ref) => {
        GetVideoList(param)
            .then((r: object) => {
                res(r.data);
                store.dispatch('pageTotal', r.total);
            })
            .catch(e => {
                ref();
            });
    });
};

// 获取 链接的数据
const getLinkListFun = (param: object) => {
    return new Promise((res, ref) => {
        linkList(param).then((r: object) => {
            res(r.data);
            store.dispatch('pageTotal', r.total);
        });
    });
};
// 获取 文本数据
const getTextListFun = (param: object) => {
    return new Promise((res, ref) => {
        getTextList(param).then((r: object) => {
            res(r.data);
            store.dispatch('pageTotal', r.total);
        });
    });
};
// 获取收集表数据
const getFormList = (param: any) => {
    return new Promise((res, ref) => {
        getCollectList(param).then((r: object) => {
            res(r.data);
            store.dispatch('pageTotal', r.total);
        });
    });
};

// 切换tabs
const handleClick = async (val: any) => {
    remainNumber.value = 0;
    const index = prop.tabsList.findIndex(it => {
        return it.label === prop.activeName;
    });
    const typeIndex = typeArr.findIndex(it => {
        return it.type === prop.activeName;
    });
    await getGroupListFun(typeArr[typeIndex].id);
    prop.tabsList[index].list = [];
    getChildData();
    emit('save', {
        type: prop.activeName
    });
};
// 获取本地链接数据
const getLocalLink = (data: any) => {
    emit('save', data);
    baseVisib.value = false;
};
const submitHandel = () => {
    if (!dialogData[prop.activeName].list.length) {
        ElMessage.error('请选择素材');
        return;
    }
    const retData = { type: prop.activeName, data: dialogData[prop.activeName].list };
    // 向父组件推送数据
    emit('save', retData);

    // 隐藏控件
    baseVisib.value = false;
    // 清空选择数组
    reinit();
};

// 关闭弹框
const closeDialog = () => {
    const arr = Object.keys(dialogData);
    arr.forEach(it => {
        chooseCirclName[it].num = 0;
        dialogData[it] = { page: 1, page_size: 15, seachKey: '', groupData: {}, list: [] };
    });
    baseVisib.value = false;
};

// 获取子组件的数据
const getDataFun = (data: any) => {
    chooseCirclName[data.type].num = data.data.length;
    for (const i in dialogData) {
        if (i != prop.activeName) {
            dialogData[i].list = [];
        }
    }
    dialogData[data.type].list = data.data;
    selet_num.value = data.data.length;
};
//
const showDialog = (activeName: string, selectLimit: any, selectData: any, len: number) => {
    // BaseDialogRef.value.prop.activeName = type ? type : form.dataType;
    if (!selectData) reinit();
    remainNumber.value = len;
    prop.activeName = activeName;
    baseVisib.value = true;
};

// 处理本地上传
const handleChange = async (file: UploadFile, list: UploadFile[]) => {
    const retData = { type: prop.activeName, data: [] };
    if (prop.activeName == 'image') {
        const data: any = await uploadImg(file);
        // 组装数据结构
        retData.data.push({
            id: 0,
            is_local: 1,
            url: data.url,
            thumbnail_url: data.url,
            absolute_url: data.url,
            code: data.code,
            name: data.name
        });
    } else {
        const data: any = await uploadImg(file);
        // 组装数据结构
        retData.data.push({
            id: 0,
            is_local: 1,
            url: data.url,
            // 视频缩略图
            thumbnail_url: getVideoThumb(data.url),
            absolute_url: data.url,
            code: data.code,
            name: data.name
        });
    }
    emit('save', retData);
    // 隐藏控件
    baseVisib.value = false;

    // 清空选择数组
    reinit();
};

const beforeUpdata = (file: any) => {
    const limitSize = 10;

    const is2M = file.size / 1024 / 1024 <= limitSize;
    let tips = '视频';
    switch (prop.activeName) {
        case 'image':
            tips = '图片';
            break;
        case 'video':
            tips = '视频';
            break;
        default:
            tips = '';
    }
    if (!is2M) {
        ElMessage.warning(`上传的${tips}最大支持${limitSize}M`);
        return;
    }
    return is2M;
};

// 上传文件
const uploadImg = async (file: any) => {
    file = file.raw;
    const flag = beforeUpdata(file);
    if (!flag) return;
    return await uploadFile2({
        file,
        fileName: file.name
    });
};
const localUploadShow = computed(function () {
    if (prop.activeName == 'image' || prop.activeName == 'video') {
        return 'upload';
    } else if (prop.activeName == 'link') {
        return 'link';
    } else {
        return false;
    }
});

const localUploadAllowFileType = computed(function () {
    switch (prop.activeName) {
        case 'image':
            return '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG';
        case 'video':
            return '.mp4';
        default:
            return '';
    }
});

const showCreatLocalLink = () => {
    CreateLocalLinkCompent.value.showDialog();
};
defineExpose({
    showDialog,
    baseVisib,
    prop,
    dialogData,
    imgLength
});
</script>
<style lang="scss" scoped>
.tab_box {
    min-height: 600px;
    position: relative;

    .group_box {
        position: absolute;
        width: 170px;
        left: 0;
        top: 40px;
        height: calc(100% - 40px);
        border-right: solid 1px #eaeaea;
    }

    .pane-box {
        padding-left: 190px;
        padding-right: 30px;
    }

    .pane-body-box {
        margin-top: 12px;
        width: 100%;
        height: 504px;
        overflow-y: scroll;
        white-space: nowrap;
    }

    .pane-body-box::-webkit-scrollbar {
        width: 0 !important;
    }

    .pane-body-box::-webkit-scrollbar {
        width: 0 !important;
        height: 0;
    }
}

.r_tab {
    position: absolute;
    top: 0;
    right: 30px;
    line-height: 40px;
}

.footer_box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row-reverse;

    .left_footer {
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        font-weight: 300;
        color: #33302d;

        span {
            color: #ff6b00;
            margin: 0 5px;
        }
    }
}

:deep(.demo-tabs) {
    .el-tabs__header {
        background: #f9f9f9;
    }

    .el-tabs__item {
        padding: 0 20px !important;
    }
}

:deep(.app_base_dialog) {
    .el-dialog__header {
        padding: 0;

        .el-dialog__headerbtn {
            .el-dialog__close {
                font-size: 20px;
            }
        }
    }

    .el-dialog__body {
        padding: 0 !important;
    }

    .dialog_header {
        height: 50px;
        display: flex;
        padding: 0 30px;
        align-items: center;
        font-size: 16px;
        font-family: PingFangSC-Medium, 'PingFang SC';
        font-weight: 500;
        color: #33302d;
        line-height: 16px;
        border-bottom: 1px solid #eaeaea;
    }

    .el-dialog__footer {
        height: 60px;
        box-sizing: border-box;
        padding: 10px 30px;
        border-top: 1px solid #eaeaea;

        .el-button {
            height: 36px;
            min-height: auto;
        }

        .upload_demo {
            display: inline-block;
            cursor: pointer;
        }
    }

    .ml20 {
        margin-left: 20px;
    }
}
</style>
